<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2025-03-05 13:24:07
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2025-03-24 14:20:02
 * @FilePath: \global-brain\global-brain-admin\src\components\Lee\Editor\src\LeeTiptapEditor.vue
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<script setup lang="ts">
import { useEditor, EditorContent } from '@tiptap/vue-3'
import { Color } from '@tiptap/extension-color'
import ListItem from '@tiptap/extension-list-item'
import StarterKit from '@tiptap/starter-kit'
import Image from '@tiptap/extension-image'
import TextStyle from '@tiptap/extension-text-style'
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import {
  // ElButtonGroup,
  ElButton,
  ElUpload,
  ElMessageBox,
  // ElSelect,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElColorPicker
} from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue'])

// 初始化编辑器
const editor = useEditor({
  content: props.modelValue,
  extensions: [
    StarterKit,
    Image.configure({
      inline: true,
      allowBase64: true
    }),
    Color.configure({ types: [TextStyle.name, ListItem.name] }),
    TextStyle.configure({ types: [ListItem.name] })
  ],
  onUpdate: () => {
    emit('update:modelValue', editor.value.getHTML())
  }
})

// 生命周期管理
onMounted(() => {
  editor.value.commands.setContent(props.modelValue)
})

onBeforeUnmount(() => {
  editor.value.destroy()
})

const selectedHeading = ref('paragraph')

// 监听编辑器状态的变化
watch(
  () => editor.value?.isActive('paragraph'),
  (isActive) => {
    if (isActive) {
      selectedHeading.value = 'paragraph'
    }
  }
)

watch(
  () => editor.value?.isActive('heading', { level: 1 }),
  (isActive) => {
    if (isActive) {
      selectedHeading.value = 'h1'
    }
  }
)

watch(
  () => editor.value?.isActive('heading', { level: 2 }),
  (isActive) => {
    if (isActive) {
      selectedHeading.value = 'h2'
    }
  }
)

watch(
  () => editor.value?.isActive('heading', { level: 3 }),
  (isActive) => {
    if (isActive) {
      selectedHeading.value = 'h3'
    }
  }
)

watch(
  () => editor.value?.isActive('heading', { level: 4 }),
  (isActive) => {
    if (isActive) {
      selectedHeading.value = 'h4'
    }
  }
)

watch(
  () => editor.value?.isActive('heading', { level: 5 }),
  (isActive) => {
    if (isActive) {
      selectedHeading.value = 'h5'
    }
  }
)

watch(
  () => editor.value?.isActive('heading', { level: 6 }),
  (isActive) => {
    if (isActive) {
      selectedHeading.value = 'h6'
    }
  }
)

// 定义下拉框的选项
const headingOptions = [
  { label: '正文', value: 'paragraph' },
  { label: 'H1', value: 'h1' },
  { label: 'H2', value: 'h2' },
  { label: 'H3', value: 'h3' },
  { label: 'H4', value: 'h4' },
  { label: 'H5', value: 'h5' },
  { label: 'H6', value: 'h6' }
]

// 处理下拉框的选择事件
const handleHeadingChange = (value: string) => {
  if (value === 'paragraph') {
    editor.value.chain().focus().setParagraph().run()
  } else {
    const level = parseInt(value.replace('h', ''), 10)
    editor.value.chain().focus().toggleHeading({ level }).run()
  }
}

// 图片上传方法
// const addImage = () => {
//   const url = window.prompt('请输入图片URL')

//   if (url) {
//     editor.value.chain().focus().setImage({ src: url }).run()
//   }
// }
// 上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code == '200') {
    // console.log(response.data.file_url)
    const url = response.data.file_url
    editor.value.chain().focus().setImage({ src: url }).run()
  } else {
    ElMessageBox.alert(response.msg, '上传失败')
  }
}

// 颜色设置
const currentColor = ref('#606266')
const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)',
  'hsv(51, 100, 100)',
  'hsva(120, 100, 100, 0.6)',
  'hsl(181, 100%, 37%)',
  'hsla(209, 100%, 56%, 0.73)',
  '#c7158577'
])

const handleColorChange = (color: string) => {
  editor.value.chain().focus().setColor(color).run()
}

watch(
  () => editor.value?.getAttributes('textStyle').color,
  (newColor) => {
    if (newColor) {
      currentColor.value = newColor
    } else {
      currentColor.value = '#606266' // 默认颜色
    }
  }
)
</script>

<template>
  <div class="editor-container">
    <!-- 自定义工具栏 -->
    <div v-if="editor" class="toolbar">
      <!-- <el-button-group> -->
      <el-dropdown trigger="click" @command="handleHeadingChange">
        <el-button>
          <span>{{
            headingOptions.find((option) => option.value === selectedHeading)?.label || '段落/标题'
          }}</span>
          <el-icon><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="option in headingOptions"
              :key="option.value"
              :command="option.value"
            >
              {{ option.label }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button
        @click="editor.chain().focus().toggleBold().run()"
        :class="{ active: editor.isActive('bold') ? true : false }"
        title="粗体"
      >
        <Icon :size="18" icon="ant-design:bold-outlined" class="cursor-pointer" />
      </el-button>
      <el-button
        @click="editor.chain().focus().toggleItalic().run()"
        :class="{ active: editor.isActive('italic') ? true : false }"
        title="斜体"
      >
        <Icon :size="18" icon="ant-design:italic-outlined" class="cursor-pointer" />
      </el-button>
      <el-button
        @click="editor.chain().focus().toggleStrike().run()"
        :disabled="!editor.can().chain().focus().toggleStrike().run()"
        :class="{ 'is-active': editor.isActive('strike') }"
        title="删除线"
      >
        <Icon :size="18" icon="ant-design:strikethrough-outlined" class="cursor-pointer" />
      </el-button>
      <el-button
        @click="editor.chain().focus().undo().run()"
        :disabled="!editor.can().chain().focus().undo().run()"
        title="撤销"
      >
        <Icon :size="18" icon="ant-design:undo-outlined" class="cursor-pointer" />
      </el-button>
      <el-button
        @click="editor.chain().focus().redo().run()"
        :disabled="!editor.can().chain().focus().redo().run()"
        title="重做"
      >
        <Icon :size="18" icon="ant-design:redo-outlined" class="cursor-pointer" />
      </el-button>

      <el-button
        @click="editor.chain().focus().toggleCode().run()"
        :disabled="!editor.can().chain().focus().toggleCode().run()"
        :class="{ 'is-active': editor.isActive('code') }"
        title="标签"
      >
        <Icon :size="18" icon="ant-design:tag-outlined" class="cursor-pointer" />
      </el-button>
      <!-- <el-button @click="editor.chain().focus().unsetAllMarks().run()"> Clear marks </el-button> -->
      <!-- <el-button @click="editor.chain().focus().clearNodes().run()"> Clear nodes </el-button> -->
      <!-- <el-button
          @click="editor.chain().focus().setParagraph().run()"
          :class="{ 'is-active': editor.isActive('paragraph') }"
        >
          Paragraph
        </el-button>
        
        -->
      <el-button
        @click="editor.chain().focus().toggleBulletList().run()"
        :class="{ 'is-active': editor.isActive('bulletList') }"
        title="无序列表"
      >
        <Icon :size="18" icon="ant-design:unordered-list" class="cursor-pointer" />
      </el-button>
      <el-button
        @click="editor.chain().focus().toggleOrderedList().run()"
        :class="{ 'is-active': editor.isActive('orderedList') }"
        title="有序列表"
      >
        <Icon :size="18" icon="ant-design:ordered-list-outlined" class="cursor-pointer" />
      </el-button>
      <el-button
        @click="editor.chain().focus().toggleCodeBlock().run()"
        :class="{ 'is-active': editor.isActive('codeBlock') }"
        title="代码块"
      >
        <Icon :size="18" icon="ant-design:code-outlined" class="cursor-pointer" />
      </el-button>
      <el-button
        @click="editor.chain().focus().toggleBlockquote().run()"
        :class="{ 'is-active': editor.isActive('blockquote') }"
        title="引用"
      >
        <Icon :size="18" icon="tabler:blockquote" class="cursor-pointer" />
      </el-button>
      <el-button @click="editor.chain().focus().setHorizontalRule().run()" title="分割线">
        <Icon :size="18" icon="ant-design:border-verticle-outlined" class="cursor-pointer" />
      </el-button>
      <el-button @click="editor.chain().focus().setHardBreak().run()" title="换行">
        <Icon :size="18" icon="ant-design:enter-outlined" class="cursor-pointer" />
      </el-button>
      <!-- <el-button
        @click="editor.chain().focus().setColor('#958DF1').run()"
        :class="{ 'is-active': editor.isActive('textStyle', { color: '#958DF1' }) }"
      >
        Purple
      </el-button> -->
      <!-- class="avatar-uploader" -->
      <!-- </el-button-group> -->

      <el-color-picker
        v-model="currentColor"
        show-alpha
        :predefine="predefineColors"
        @change="handleColorChange"
      />
      <ElUpload
        class="avatar-uploader"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :action="appStore.getUploadUrl"
      >
        <el-button title="上传图片">
          <Icon :size="18" icon="ant-design:file-image-outlined" class="cursor-pointer" />
          上传图片
        </el-button>
      </ElUpload>
    </div>

    <!-- 编辑器内容区域 -->
    <editor-content :editor="editor" />
  </div>
</template>
